<!DOCTYPE html>  
<meta charset="utf-8" />  
<title>WebSocket Test</title>  
<script language="javascript"type="text/javascript">
    // var wsUri = "ws://jieyan.xyitech.com/control/create?fid=30"
    var wsUri = "ws://jieyan.xyitech.com/update/create"
    // var wsUri = "ws://jieyan.xyitech.com/control/create?fid=30"
    // var wsUri = "ws://jieyan.xyitech.com/observer/create?fid=1"
    // var wsUri ="ws://echo.websocket.org/"; 
    var output;  
    
    function init() { 
        output = document.getElementById("output"); 
        testWebSocket(); 
    }  
 
    function testWebSocket() { 
        websocket = new WebSocket(wsUri); 
        websocket.onopen = function(evt) { 
            onOpen(evt) 
        }; 
        websocket.onclose = function(evt) { 
            onClose(evt) 
        }; 
        websocket.onmessage = function(evt) { 
            onMessage(evt) 
        }; 
        websocket.onerror = function(evt) { 
            onError(evt) 
        }; 
    }  
 
    function onOpen(evt) { 
        writeToScreen("CONNECTED"); 
        // 10{"fid":30}
        setInterval(
            doSend,
            1000
            )
        // doSend({"id":30}); 
    }  
 
    function onClose(evt) { 
        writeToScreen("DISCONNECTED"); 
    }  
 
    function onMessage(evt) { 
        writeToScreen('<span style="color: blue;">RESPONSE: '+ evt.data+'</span>'); 
    }  
 
    function onError(evt) { 
        writeToScreen('<span style="color: red;">ERROR:</span> '+ evt.data); 
    }  
 
    function doSend(message) {
        
        // var msg = [249,1, 'abcdef']
        // websocket.send(JSON.stringify(msg));
        // var msg = [105,1, 0, 1, 1, 111,222,333,444]
        // websocket.send(JSON.stringify(msg));
        message = message ||{"id":30}
        var ab = new ArrayBuffer(4);
        var buffer = new DataView(ab);
        var str = JSON.stringify(message)
        
        buffer.setUint32(0, 4 + str.length, true);
        console.log(str.length)
        writeToScreen("SENT: "  + buffer.getUint32(0)); 
        websocket.send(buffer);
        writeToScreen("SENT: "  + str); 
        console.log(buffer)
        websocket.send(str);
    }  
 
    function writeToScreen(message) { 
        var pre = document.createElement("p"); 
        pre.style.wordWrap = "break-word"; 
        pre.innerHTML = message; 
        output.appendChild(pre); 
    }

    function onEnterDown(event) { 
        if (event.keyCode == 13) { 
            doSend(document.getElementById("input").value)
            document.getElementById("input").value = null
        }
    }
    window.addEventListener("load", init, false);  
</script>  
<h2>WebSocket Test</h2>  
<div id="output"></div>

<input type="text" id="input" onkeydown="return onEnterDown(event)"/>

</html>